﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Leo.Awesome.DictionaryManagement.Domain;
using Volo.Abp.DependencyInjection;

namespace Leo.Awesome.DictionaryManagement.DomainServices
{
    public interface ISectionDataSeeder
    {

        Task SeedAsync(List<Section> sections,string domain= "default");

        Task<List<Section>> GetAllAsync(string domain="default");  
    }

    public class SectionDataSeeder : ITransientDependency, ISectionDataSeeder
    {
        private readonly ISectionRepository sectionRepository;

        public SectionDataSeeder(ISectionRepository sectionRepository)
        {
            this.sectionRepository = sectionRepository;
        }
        public virtual async Task SeedAsync(List<Section> sections, string domain = "default")
        {
            if (sections.IsNullOrEmpty())
            {
                return;
            }
            var codes = sections.Where(x=>x.IsSection).Select(x => x.Code).ToList();
            var entites = await sectionRepository.GetListAsync(x => codes.Contains(x.Code)
            && x.Domain == domain);
            //if (entites.Any())
            //{
            //    return;
            //}
            sections.ForEach(x =>
            {
                SetDomainRecursive(x, domain);
            });

            sections = sections.Where(x => x.IsSection).ToList();
            var existCodes = entites.Select(x => x.Code).ToList();


            foreach (var code in codes.Except(existCodes))
            {
                var section = sections.FirstOrDefault(x => x.Code == code);
                if (section != null)
                {
                    await sectionRepository.InsertAsync(section);
                }
            }
        }

        private static void SetDomainRecursive(Section section, string domain)
        {
            section.Domain = domain;

            foreach (var item in section.Items)
            {
                SetDomainRecursive(item, domain);
            }
        }

        public async Task<List<Section>> GetAllAsync(string domain = "default")
        {
            return await sectionRepository.GetListAsync(x=>x.Domain == domain); 
        }
    }
}
